import type { FormInstance } from '@/YmForm/interface';
import { useCallback, useRef } from 'react';

export const useFormInstanceObserves = () => {
  const formInstanceRefs = useRef<Map<string, FormInstance>>(new Map());

  const addFormInstance = useCallback<
    (currRowKey: string, rowFormInstance: FormInstance) => void
  >((currRowKey, rowFormInstance) => {
    formInstanceRefs.current.set(currRowKey, rowFormInstance);
  }, []);

  const removeFormInstance = useCallback<(currRowKey: string) => void>(
    (currRowKey) => {
      formInstanceRefs.current.delete(currRowKey);
    },
    [],
  );

  //验证
  const validateObservers = useCallback<() => Promise<any>>(() => {
    const formInstances = [...(formInstanceRefs.current.values() as any)];
    return Promise.all(
      formInstances.map((formInstance) => formInstance.validateFields()),
    );
  }, []);

  //重置
  const formResetObservers = useCallback<
    (
      fieldNames: string[],
      currRowKey?: string,
    ) => Record<string, any> | Record<string, any>[]
  >((fieldNames, currRowKey) => {
    if (currRowKey !== undefined && currRowKey !== null) {
      const currRowFormInstance = formInstanceRefs.current.get(currRowKey!);
      currRowFormInstance?.resetFields(fieldNames);
      const newCurrRowData = currRowFormInstance?.getFieldsValue('all');
      return newCurrRowData;
    } else {
      const newRowsData = [];
      const formInstances = [...(formInstanceRefs.current.values() as any)];
      for (let i = 0; i < formInstances.length; i++) {
        formInstances[i].resetFields(fieldNames);
        const newCurrRowData = formInstances[i].getFieldsValue('all');
        newRowsData.push(newCurrRowData);
      }
      return newRowsData;
    }
  }, []);

  const getFormInstances = useCallback<
    (currRowKey: string) => FormInstance | Map<string, FormInstance> | undefined
  >((currRowKey) => {
    if (currRowKey !== undefined && currRowKey !== null) {
      return formInstanceRefs.current.get(currRowKey);
    }
    return formInstanceRefs.current;
  }, []);

  return {
    addFormInstance,
    removeFormInstance,
    validateObservers,
    getFormInstances,
    formResetObservers,
  };
};
